﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using MiniStock.BusinessLogic.EventQueue.Queue;
using MiniStock.Entities.Common.Events;
using MiniStock.Infrastructure;
using Microsoft.Practices.Unity;
using MiniStock.Infrastructure.Queue;


namespace MiniStock.BusinessLogic.EventDispatcher
{
    public class EventDispatcherLogic: BusinessLogicBase
    {
        public EventDispatcherWorker DispatcherWorker { get; set; }
        
        public EventDispatcherLogic([Dependency] EventDispatcherWorker dispatcherWorker)
        {
            DispatcherWorker = dispatcherWorker;
            DispatcherWorker.Configure();
        }


        public Guid SubmitEvent(EventBase message)
        {
            if (message.CorrelatedEventId == null)
                message.CorrelatedEventId = message.EventId;

            message.EventDate = DateTime.UtcNow;

            Trace.CorrelationManager.ActivityId = message.CorrelatedEventId ?? message.EventId;

            try
            {
                Trace.TraceInformation("EventDispatcherLogic.SubmitEvent {0} (id: {1}, cid: {2})", message,
                                       message.EventId,
                                       message.CorrelatedEventId);

                PerformanceMonitoring.IncrementCounter("Events received", message.GetType().Name);
                PerformanceMonitoring.IncrementCounter("Events received per second", message.GetType().Name);


                DispatcherWorker.AddEvent(message);
                return message.EventId;
            }
            finally
            {

            }
        }

        public StatusQueryEvent GetResult(Guid correlationId)
        {

            Trace.CorrelationManager.ActivityId = correlationId;
            try
            {
                Trace.TraceInformation("EventDispatcherLogic.GetResult (cid: {0})", correlationId);

                var mapEntry = DispatcherWorker.MapHandler.GetResult(correlationId, true);
                return mapEntry;
            }
            finally
            {
                Trace.CorrelationManager.ActivityId = Guid.Empty;
            }
        }
    }
}
